/* eslint-disable arrow-parens */
const fs = eval('require')('fs');
const path_ = eval('require')('path');
const eventClass = require('./../eventClass');
const { walk, walkTree } = require('./walk');
const unlinkDir = require('./unlinkDir');
const mkdirs = require('./mkdirs');
const copyDir = require('./copyDir');

class dirClass extends eventClass {
    constructor() {
        super('dirClass');
    }

    isEmpty(cb, { path }) {
        let len = 0;
        let err = null;
        try {
            if (fs.existsSync(path)) {
                if (fs.statSync(path).isFile()) {
                    err = new Error('该文件不是文件夹');
                } else {
                    len = fs.readdirSync(path).length;
                }
            } else {
                err = new Error('路径不存在');
            }
        } catch (e) {
            err = e;
        } finally {
            this.returnMethod(cb, {
                err,
                data: `${len}`,
            });
        }
    }

    getAll(cb, { path, childPath, isTree, excludePath }) {
        let ret = null;
        let err = null;
        path = path_.resolve(path);
        try {
            ret = isTree ? walkTree(path, childPath, excludePath) : walk(path, childPath, excludePath);
        } catch (e) {
            err = e;
        } finally {
            this.returnMethod(cb, {
                err,
                data: ret,
            });
        }
    }

    /**
     * 获取文件夹下的所有文件，不包含子文件夹
     * @param path  路径
     * @param ext   指定扩展名（可选）（数组）
     */
    getFilesUnderPath(cb, { path, ext, withInfo }) {
        path = path_.resolve(path);
        let files = fs.readdirSync(path);
        if (withInfo) {
            files = files.map((_) => {
                const state = fs.statSync(path_.join(path, _));
                return {
                    name: _,
                    state,
                    isDir: state.isDirectory(),
                };
            });
        }
        if (ext && ext.length) {
            this.returnMethod(cb, {
                data: files.filter((file) => {
                    const f = withInfo ? file.name.split('.') : file.split('.');
                    return ext.includes(f[f.length - 1]);
                }),
            });
        } else {
            this.returnMethod(cb, {
                data: files,
            });
        }
    }

    mkdir(cb, { path }) {
        path = path_.resolve(path);
        mkdirs.sync(path);
        this.returnMethod(cb, { err: null, data: true });
    }

    removeFileOrDir(cb, { path }) {
        let err = null;
        try {
            path = path_.resolve(path);
            if (fs.statSync(path).isDirectory()) { // recurse
                unlinkDir(path);
            } else { // delete file
                fs.unlinkSync(path);
            }
        } catch (e) {
            err = e;
        } finally {
            this.returnMethod(cb, {
                err,
            });
        }
    }

    copyDirSync(cb, { src, dist, withPath }) {
        copyDir.sync(src, dist, withPath);
        this.returnMethod(cb, {});
    }

    copyDir(cb, { src, dist, withPath }) {
        copyDir.async((function (callback, obj) {
            this.returnMethodAsync(callback, obj);
        }).bind(this, cb), src, dist, withPath);
    }

    /**
     * 检查多个文件是否存在
     * @param cb
     * @param folders [ ['c:\\','windows','system32'], ['c:\\','user'] ]
     */
    checkFoldersExsit(cb, { folders }) {
        this.returnMethod(cb, {
            data: folders.map(_ => path_.join(..._))
                .map(_ => {
                    return {
                        name: _,
                        exist: fs.existsSync(_),
                    };
                }),
        });
    }
}

module.exports = dirClass;
